﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using PhysicsControlModule.Models;

namespace PhysicsControlModule.Daos
{
    public class AdmQuestionDao
    {
        public static int GetCount(int labworkId)
        {
            using (CmDbEntities db = new CmDbEntities())
                return (
                    from aq in db.AdmQuestion
                    from rlaq in db.RelLabworkAdmQuestion
                    where rlaq.LabworkId == labworkId
                    where rlaq.QuestionId == aq.Id
                    select aq).Count();
        }

        public static int GetAnsweredCount(int labworkId, int userId)
        {
            using (CmDbEntities db = new CmDbEntities())
                return (
                    from aq in db.AdmQuestion
                    from rluqa in db.RelLabworkUserAdmQuestionAnswer
                    from rqa in db.RelAdmQuestionAnswer
                    where aq.Id == rluqa.QuestionId
                    where rluqa.LabworkId == labworkId
                    where rluqa.UserId == userId
                    where rluqa.QuestionId == rqa.QuestionId
                    where rqa.AnswerId == rluqa.AnswerId
                    select aq).Count();
        }

        public static int GetRightCount(int labworkId, int userId)
        {
            using (CmDbEntities db = new CmDbEntities())
                return (
                    from aq in db.AdmQuestion
                    from rluqa in db.RelLabworkUserAdmQuestionAnswer
                    from rqa in db.RelAdmQuestionAnswer
                    where aq.Id == rluqa.QuestionId
                    where rluqa.LabworkId == labworkId
                    where rluqa.UserId == userId
                    where rluqa.QuestionId == rqa.QuestionId
                    where rqa.IsTrueAnswer == true
                    where rqa.AnswerId == rluqa.AnswerId
                    select aq).Count();
        }

        public static AdmQuestion GetUnanswered(int labworkId, int userId)
        {
            using (CmDbEntities db = new CmDbEntities())
            {
                int groupId = (int) UserDao.GetById(userId).GroupId;
                return (
                    from aq in db.AdmQuestion 

                    from rlq in db.RelLabworkAdmQuestion
                    where rlq.LabworkId == labworkId
                    where aq.Id == rlq.QuestionId

                    where !db.RelLabworkUserAdmQuestionAnswer.Any(rluga => rluga.QuestionId == aq.Id && rluga.UserId == userId)

                    from rlg in db.RelLabworkGroup
                    where rlg.GroupId == groupId
                    where rlg.LabworkId == rlq.LabworkId

                    select aq).FirstOrDefault();
            }
        }
    }
}